<template>
  <div class="create-ad">
    <dt-info ref="formRef" :options="options" :info="editInfo" :label-width="120"></dt-info>
    <div class="flex flex-horizontal-center">
      <Button style="margin-right: 8px" @click="onCancel">取消</Button>
      <Button type="primary" style="margin-right: 8px" @click="onPreview" v-if="direct != 1">预览</Button>
      <Button type="primary" @click="onSave" :loading="loading">保存</Button>
    </div>
    <!--预览-->
    <preview ref="preview"></preview>
    <!--关联广告-->
    <association ref="association" @getAc="getAc"></association>
  </div>
</template>

<script>
  import createOpt from './opt/create.js'
  import adMgr from '@/biz/backStage/advertisement'
  import preview from './components/preview.vue'
  import association from './components/association.vue'
  export default {
    data() {
      return {
        direct: 3, // 直接跳转-1   详情页跳转-2   没选中-3
        isSpecial: false,
        options: [],
        editInfo: {
          name: '',
          type: 'NORMAL',
          appAnnex: [],
          appImgUrl: '',
          pcAnnex: [],
          orgIdList: [],
          portList: [],
          pcImgUrl: '',
          businessId: null,
          content: '',
          businessType: 'MARKETING_ACTIVITY',
          skipMode: null,
          buttonText: ''
        },
        advId: null,
        tabVal: '1',
        loading: false,
        acName: ''
      }
    },
    components: {
      preview,
      association
    },
    mounted() {
      this.advId = this.$route.query.advId || null
      this.tabVal = this.$route.query.tabVal || '1'
      if (this.advId) {
        setTimeout(() => {
          this.getDetail()
        }, 100)
      } else {
        this.updateForm()
      }
    },
    methods: {
      // 表单校验
      async checkForm() {
        let flag = false
        let res = await this.$refs.formRef.validate()
        if (res) {
          if (this.editInfo.type == 'NORMAL') {
            if (!this.editInfo.appImgUrl && !this.editInfo.pcImgUrl) {
              this.$Message.error('APP Banner或PC Banner二者必传其一')
              return flag
            }
          } else {
            if (!this.editInfo.businessId) {
              this.$Message.error('请选择关联内容')
              return flag
            }
            if (!this.editInfo.appImgUrl) {
              this.$Message.error('请上传APP Banner')
              return flag
            }
          }
          flag = true
        }
        return flag
      },
      // 更新表单
      updateForm() {
        this.options = createOpt.options(this)
      },
      // 查看关联
      searchAbout() {
        this.$refs.association.show(this.editInfo.businessId)
      },
      // 添加关联  变更关联
      openAc() {
        this.$refs.association.show()
      },
      // 获取关联广告
      getAc(v) {
        this.acName = v.name
        this.editInfo.businessId = v.acId
        this.updateForm()
      },
      getDetail() {
        let params = {
          id: this.advId
        }
        adMgr.getAdvertisementById(params).then((res) => {
          console.log('详情数据', res)
          if (res.appImgUrl) {
            res.appAnnex = [
              {
                name: 'APP.png',
                url: res.appImgUrl
              }
            ]
          } else {
            res.appAnnex = []
          }
          if (res.pcImgUrl) {
            res.pcAnnex = [
              {
                name: 'PC.png',
                url: res.pcImgUrl
              }
            ]
          } else {
            res.pcAnnex = []
          }
          if (res.businessName) {
            this.acName = res.businessName
          }
          if (res.type == 'SPECIAL') {
            this.isSpecial = true
          }
          if (res.skipMode == 'DIRECT') {
            this.direct = 1
          } else if (res.skipMode == 'DETAIL_PAGE') {
            this.direct = 2
          }
          this.editInfo.orgIdList = [...res.orgIdList]
          this.editInfo = { ...res }
          this.updateForm()
        })
      },
      onCancel() {
        this.$Modal.confirm({
          title: '<p>未保存的数据将会丢失，确定要离开此页吗？</p>',
          okText: '离开此页',
          cancelText: '留在此页',
          width: '450',
          onOk: () => {
            this.$router.push({
              name: 'advertisement',
              query: {
                tabVal: this.tabVal
              }
            })
          },
          onCancel: () => {}
        })
      },
      checkImageWH(file, width, height) {
        let self = this
        return new Promise(function (resolve, reject) {
          let filereader = new FileReader()
          filereader.onload = (e) => {
            let src = e.target.result
            const image = new Image()
            image.onload = function () {
              if (this.width != width || (height && this.height != height)) {
                self.$Message.error(`请上传宽为${width}px，高为${height}px的图片`)
                reject(false)
              }
              {
                resolve(true)
              }
            }
            image.onerror = reject
            image.src = src
          }
          filereader.readAsDataURL(file)
        })
      },
      async onPreview() {
        if (!(await this.checkForm())) return
        await this.submitFun()
        this.editInfo.origin = 'set'
        this.$refs.preview.show(this.editInfo)
      },
      submitFun() {
        let params = {
          ...this.editInfo
        }
        if (this.advId || this.editInfo.id) {
          return adMgr.updateFun(params).then((res) => {
            this.$Message.success('更新成功')
          })
        } else {
          return adMgr.createFun(params).then((res) => {
            this.editInfo.id = res
            this.$Message.success('新建成功')
          })
        }
      },
      async onSave() {
        // console.log(this.editInfo)
        // return
        if (!(await this.checkForm())) return
        this.loading = true
        await this.submitFun()
        this.loading = false
        this.$router.push({
          name: 'advertisement',
          query: {
            tabVal: this.tabVal
          }
        })
      }
    }
  }
</script>

<style>
  .create-ad {
    padding: 20px;
  }
</style>
